#include <pthread.h>
#include <stdio.h>
#include <assert.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;


int g_shared_counter = 1;
static void * task_thread_run(){
    //lock 
    assert(0 == pthread_mutex_lock(&mutex));
    {
        //do something in task thread
        g_shared_counter++;
        printf("task_thread is running, sub thread increase the g_shared_counter = %d\n", g_shared_counter);
    }
    // signal the wait
    assert(0 == pthread_cond_signal(&cond));
    assert(0 == pthread_mutex_unlock(&mutex));
}

int main(){
    printf("main thread is running, g_shared_counter = %d\n", g_shared_counter);

    pthread_t tid;
    assert(0 == pthread_create(&tid, NULL , task_thread_run, NULL));

    printf("main thread wait for decrease g_shared_counter");
    //lock first 
    assert(0 == pthread_mutex_lock(&mutex));

    //wait & lock
    assert(0 == pthread_cond_wait( &cond, &mutex ));
    {
        //do something in main thread
        g_shared_counter--;
        printf("back to main thread, g_shared_counter= %d \n" , g_shared_counter);
    }
    //unlock
    assert(0 == pthread_mutex_unlock(&mutex));

    return 0;

}
